<template>
  <div class="city-list">
    <div class="city-box" ref="wrapper">
      <div class="city-box-content">
        <div class="city-box-item" v-for="arr of appendCities" :key="arr[0]">
          <!--   标签     -->
          <div class="index-label" :id="arr[0]">{{ arr[0] }}</div>
          <div class="cities">
            <div class="city" v-for="{ id, nm } in arr[1]" :key="id">
              {{ nm }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="city-index-list" @click="clickIndexHander">
      <div
        v-for="{ title, value } in cityIndexes"
        :key="value"
        :data-target="`#${value}`"
      >
        {{ title }}
      </div>
    </div>
  </div>
</template>

<script>
import { getCitis } from "../api/index";
import { save, restore } from "../util/cache";
import { groupBy, map, sortBy } from "lodash"; // lodash 500+kb
import BScroll from "@better-scroll/core";

import MouseWheel from "@better-scroll/mouse-wheel";
BScroll.use(MouseWheel);

const CACHE_KEY = "cities";
export default {
  name: "CityList",
  props: {},
  data: function() {
    return {
      cities: []
    };
  },
  created() {
    this.bScroll = null;
  },
  async mounted() {
    await this.requestCities();
    this.$nextTick(() => {
      this.bScroll = new BScroll(this.$refs["wrapper"], {
        scrollY: true,
        probeType: 3,
        mouseWheel: {
          speed: 20,
          invert: false,
          easeTime: 300
        }
      });
      this.bScroll.on("scroll", function({ x, y }) {
        console.log(x, y);
      });
    });
  },
  computed: {
    groupCities: function() {
      /**
       * {cts:{py:'bj',nm:'北京'},{py:'als',nm:'阿拉善'}}
       * groupBy
       * {B:[{py:'bj',nm:'北京'}],A:[{py:'als',nm:'阿拉善'}]}
       * map
       * [['B',[{py:'bj',nm:'北京'}],['A',[{py:'als',nm:'阿拉善'}]]]
       * sortBy
       * [['A',[{py:'als',nm:'阿拉善'}]],['B',[{py:'bj',nm:'北京'}]]
       * @type {Object}
       */
      const groupCities = groupBy(this.cities, ({ py }) => {
        // 返回的是分组的键值
        return py.slice(0, 1).toUpperCase();
      });
      // map遍历对象（当然也能遍历数组）
      // [[key,value],[key,value]....]
      return map(groupCities, (value, key) => {
        return [key, value];
      });
    },
    sortedCities: function() {
      // 对数组进行排序，第二个参数iteratees是一个function，返回值用于排序。
      return sortBy(this.groupCities, arr => {
        // ['A',[{py:'als',nm:'阿拉善'}]]
        // return B,A,C,D
        return arr[0];
      });
    },
    appendCities: function() {
      return Array.prototype.concat.call(
        [["定位城市", [{ py: "dingweishibai", nm: "定位失败", id: "000" }]]],
        [
          [
            "热门城市",
            [
              { py: "beijing", nm: "北京", id: "bj" },
              { py: "shanghai", nm: "上海", id: "sh" },
              { py: "guangzhou", nm: "广州", id: "gz" },
              { py: "shenzhen", nm: "深圳", id: "sz" }
            ]
          ]
        ],
        this.sortedCities
      );
    },
    cityIndexes: function() {
      return map(this.appendCities, arr => {
        return {
          title: arr[0].replace("城市", ""),
          value: arr[0]
        };
      });
    }
  },
  methods: {
    requestCities: async function() {
      // const cachedCts = restore(CACHE_KEY);
      // console.log(cachedCts)
      // if (cachedCts) {
      //   this.cities = cachedCts;
      // } else {
      const data = await getCitis();
      const { cts } = data;
      save(CACHE_KEY, cts);
      this.cities = cts;
      // }
    },
    clickIndexHander: function(e) {
      if (e.target) {
        const target = e.target.getAttribute("data-target");
        if (target) {
          this.bScroll.scrollToElement(target, 300);
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.city-list {
  height: 100%;
  color: #333333;
  .city-box {
    // 承载所有城市选择的容器
    height: 100%;
    background: #ebebeb;
    .city-box-content {
      height: auto;
      .city-box-item {
        &:nth-child(1),
        &:nth-child(2) {
          .cities {
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            align-items: flex-start;
            padding-bottom: 0.15rem;
            .city {
              margin-left: 0.15rem;
              background: #fff;
              width: 29%;
              height: 33px;
              margin-top: 15px;
              padding: 0 4px;
              border: 1px solid #e6e6e6;
              border-radius: 3px;
              line-height: 33px;
              text-align: center;
              box-sizing: border-box;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              margin-right: -0.05rem;
            }
          }
        }
        .index-label {
          margin-left: 0.1rem;
          font-size: 0.14rem;
          line-height: 0.3rem;
          vertical-align: center;
        }
        .cities {
          background: #f5f5f5;
          .city {
            line-height: 0.44rem;
            border-bottom: 1px solid #c8c7cc;
            margin-left: 0.15rem;
          }
        }
      }
    }
  }
}
.city-index-list {
  position: fixed;
  right: 0;
  z-index: 100;
  top: 50%;
  height: auto;
  transform: translateY(-50%);
  text-align: right;
  margin-right: 0.1rem;
  font-size: 0.12rem;
  line-height: 150%;
}
/*.city-list-container{*/
/*  height:500px;*/
/*  overflow: scroll;*/
/*}*/
</style>
